#include "javanative.h"
#include "simpleCustomEvent.h"

#include <QApplication>
#include <QDebug>

#ifdef ANDROID
#include <QAndroidJniEnvironment>
#include <QAndroidJniObject>
#include <jni.h>
#endif

namespace GVAL_Gather {
    extern QObject *g_listener;
}

static void OnNotify_MSG(JNIEnv *env, jobject /*thiz*/,int index,jstring msg)
{
    try{
        QString qmsg;
        const char *nativeString = env->GetStringUTFChars(msg, 0);
        qmsg = QString("%1").arg(nativeString);
        env->ReleaseStringUTFChars(msg, nativeString);
//        qInfo() << "msg=" << qmsg;
        QCoreApplication::postEvent(GVAL_Gather::g_listener, new SimpleCustomEvent(1, qmsg,index));
    }catch(...){
        qDebug() << "OnNotify_MSG Exception";
    }
}

static void OnNotify_LOG(JNIEnv *env, jobject /*thiz*/,jstring log)
{
    try{
        QString qlog;
        const char *nativeString = env->GetStringUTFChars(log, 0);
        qlog = nativeString;
        env->ReleaseStringUTFChars(log, nativeString);
        qInfo() << "log=" << qlog;
        QCoreApplication::postEvent(GVAL_Gather::g_listener, new SimpleCustomEvent(2, qlog));
    }catch(...){
        qDebug() << "OnNotify_LOG Exception";
    }
}

bool registerNativeMethods()
{
    try{
        JNINativeMethod methods[] {
            {"OnNotify_MSG", "(ILjava/lang/String;)V", (void*)OnNotify_MSG},
            {"OnNotify_LOG", "(Ljava/lang/String;)V", (void*)OnNotify_LOG}
        };

        const char *classname = "an/qt5/javagather/PL2303HXDNative";
        jclass clazz;
        QAndroidJniEnvironment env;

        QAndroidJniObject javaClass(classname);
        clazz = env->GetObjectClass(javaClass.object<jobject>());
        qInfo() << "find PL2303HXDNative - " << clazz;
        bool result = false;
        if(clazz)
        {
            jint ret = env->RegisterNatives(clazz,
                                            methods,
                                            sizeof(methods) / sizeof(methods[0]));
            env->DeleteLocalRef(clazz);
            qInfo() << "RegisterNatives return - " << ret;
            result = ret >= 0;
        }
        if(env->ExceptionCheck())
            env->ExceptionClear();
        return result;
    }catch(...){
        qDebug() << "registerNativeMethods Exception";
        return false;
    }
}
